import random
import four_white_detect


# 定义棋盘大小
BOARD_SIZE = 3


# 初始化棋盘
def initialize_board():
    return [[' ' for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]


# 打印棋盘
def print_board(board):
    for row in board:
        print('| ' + ' | '.join(row) + ' |')
        print('+' + '---+' * BOARD_SIZE)


# 检查是否有玩家获胜
def check_win(board, player):
    # 检查行和列
    for i in range(BOARD_SIZE):
        if all(board[i][j] == player for j in range(BOARD_SIZE)) or \
                all(board[j][i] == player for j in range(BOARD_SIZE)):
            return True
    # 检查对角线
    if all(board[i][i] == player for i in range(BOARD_SIZE)) or \
            all(board[i][BOARD_SIZE - 1 - i] == player for i in range(BOARD_SIZE)):
        return True
    return False


# 检查是否平局
def check_draw(board):
    return all(board[i][j] != ' ' for i in range(BOARD_SIZE) for j in range(BOARD_SIZE))


# AI使用Minimax算法找到最佳下棋位置
def minimax(board, depth, is_maximizing):
    if check_win(board, 'X'):
        return -1
    elif check_win(board, 'O'):
        return 1
    elif check_draw(board):
        return 0

    if is_maximizing:
        best_score = -float('inf')
        for i in range(BOARD_SIZE):
            for j in range(BOARD_SIZE):
                if board[i][j] == ' ':
                    board[i][j] = 'O'
                    score = minimax(board, depth + 1, False)
                    board[i][j] = ' '
                    best_score = max(score, best_score)
        return best_score
    else:
        best_score = float('inf')
        for i in range(BOARD_SIZE):
            for j in range(BOARD_SIZE):
                if board[i][j] == ' ':
                    board[i][j] = 'X'
                    score = minimax(board, depth + 1, True)
                    board[i][j] = ' '
                    best_score = min(score, best_score)
        return best_score


# AI选择最佳移动，可以指定初始位置
def get_best_move(board, initial_move=None):
    if initial_move:
        if board[initial_move[0]][initial_move[1]] == ' ':
            return initial_move

    best_score = -float('inf')
    best_move = None
    for i in range(BOARD_SIZE):
        for j in range(BOARD_SIZE):
            if board[i][j] == ' ':
                board[i][j] = 'O'
                score = minimax(board, 0, False)
                board[i][j] = ' '
                if score > best_score:
                    best_score = score
                    best_move = (i, j)
    return best_move


init_count = 0
board = 0
# 主游戏循环
def main_function(get_row,get_col,get_init_row,get_init_col):
    global init_count
    global board
    if init_count == 0:
        board = initialize_board()

        # 选择AI的初始位置
        initial_move = (get_init_row,get_init_col)  # 这里设置AI的初始位置为棋盘的中间位置

        # AI先手
        print("电脑在思考中...")
        ai_move = get_best_move(board, initial_move)
        print("ai_move", ai_move)
        print("ai为O，人为X")
        board[ai_move[0]][ai_move[1]] = 'O'
        current_player = 'X'  # 切换到玩家下棋
        init_count += 1
        return

    print_board(board)

    while True:
        try:
            # row = int(input("请输入行号 (0, 1, 2): "))
            row = get_row
            # col = int(input("请输入列号 (0, 1, 2): "))
            col = get_col
            if board[row][col] == ' ':
                board[row][col] = 'X'
                break
            else:
                print("这个位置已经被占据了，请重新输入。")
        except ValueError:
            print("请输入有效的行号和列号。")

    # 判断游戏状态
    if check_win(board, 'X'):
        print_board(board)
        print(f"恭喜，人获胜！")
        return
    elif check_draw(board):
        print_board(board)
        print("游戏结束，平局！")
        return

    # AI下棋
    print("电脑在思考中...")
    ai_move = get_best_move(board)
    print("ai_move", ai_move)
    print("ai为O，人为X")
    out_row = ai_move[0]
    out_col = ai_move[1]
    board[ai_move[0]][ai_move[1]] = 'O'

    # 判断游戏状态
    if check_win(board, 'O'):
        print_board(board)
        print("很遗憾，电脑获胜！")
        return
    elif check_draw(board):
        print_board(board)
        print("游戏结束，平局！")
        return

    return out_row,out_col

